<template>
  <el-dialog :title="`${isEdit ? '编辑' : '新增'}计量设备`" :model-value="modelValue" width="700px" @close="commEvent.onClose">
    <el-form ref="formRef" :model="formValue" :rules="formRules">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属厂区" prop="factoryId">
            <el-select
              v-model="formValue.factoryId"
              placeholder="请选择所属厂区"
              filterable
              :disabled="isEdit"
              @change="commEvent.getDevices"
            >
              <el-option v-for="(item, index) in factorys" :key="index" :label="item.label" :value="item.value || ''" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属产线" prop="lineId">
            <el-select
              v-model="formValue.lineId"
              placeholder="请选择所属产线"
              filterable
              :disabled="isEdit"
              @change="commEvent.getDevices"
            >
              <el-option v-for="(item, index) in lines" :key="index" :label="item.label" :value="item.value || ''" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属设备" prop="deviceId">
            <el-select v-model="formValue.deviceId" :disabled="isEdit" placeholder="请选择所属设备" filterable>
              <el-option
                v-for="item in devcieOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属网关" prop="gatewayCode">
            <el-select v-model="formValue.gatewayCode" :disabled="isEdit" placeholder="请选择所属网关" filterable clearable>
              <el-option v-for="(item, index) in gateWays" :key="index" :label="item.label" :value="item.value || ''" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备编码" prop="code">
            <el-input v-model="formValue.code" :disabled="isEdit" placeholder="请输入设备编码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备名称" prop="name">
            <el-input v-model="formValue.name" placeholder="请输入设备名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备类型" prop="meterType">
            <el-select v-model="formValue.meterType" :disabled="isEdit" placeholder="请选择设备类型" filterable>
              <el-option v-for="(item, index) in devicetTypes" :key="index" :label="item.label" :value="item.value || ''" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="能源类型" prop="energyType">
            <el-select v-model="formValue.energyType" :disabled="isEdit" placeholder="请选择能源类型" filterable>
              <el-option v-for="(item, index) in energyTypeEnum" :key="index" :label="item.label" :value="item.value || ''" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="通讯模式" prop="commsMode">
            <el-select v-model="formValue.commsMode" :disabled="isEdit" placeholder="请选择通讯模式" filterable>
              <el-option v-for="(item, index) in commModes" :key="index" :label="item.label" :value="item.value || ''" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="安装位置" prop="location">
            <el-input v-model="formValue.location" placeholder="请输入安装位置" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规格型号" prop="modelNumber">
            <el-input v-model="formValue.modelNumber" placeholder="请输入规格型号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生产厂家" prop="manufacturer">
            <el-input v-model="formValue.manufacturer" placeholder="请输入生产厂家" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生产日期" prop="productionDate">
            <el-date-picker
              v-model="formValue.productionDate"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择生产日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="投运日期" prop="putrunDate">
            <el-date-picker
              v-model="formValue.putrunDate"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择投运日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责人" prop="personCharge">
            <el-input v-model="formValue.personCharge" placeholder="请输入负责人姓名" />
          </el-form-item>
        </el-col>
        <template v-if="formValue.energyType === 'electric'">
          <el-col :span="12">
            <el-form-item label="停机电流阈值" prop="rangeCurrentStop">
              <el-input v-model="formValue.rangeCurrentStop" type="number" placeholder="请输入停机电流阈值">
                <template #append>A</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="待机电流阈值" prop="rangeCurrentWait">
              <el-input v-model="formValue.rangeCurrentWait" type="number" placeholder="请输入待机电流阈值">
                <template #append>A</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电流上限阈值" prop="rangeCurrentUpper">
              <el-input v-model="formValue.rangeCurrentUpper" type="number" placeholder="请输入电流上限阈值">
                <template #append>A</template>
              </el-input>
            </el-form-item>
          </el-col>
        </template>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formValue.remark" type="textarea" :rows="3" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="commEvent.onClose">取消</el-button>
      <el-button type="primary" @click="commEvent.onSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, nextTick, PropType, ref, watch } from "vue"
import { ElMessage, FormInstance, FormRules } from "element-plus"
import { EnumProps } from "@/components/ProTable/interface"
import { energyTypeEnum } from "@/utils/enum"
import { addMeter, deviceIdsBound, deviceList, modifyMeter, meterDetail } from "@/api/modules/archive"
import { SystemSpace } from "@/api/interface/archive"
const props = defineProps({
  modelValue: Boolean,
  rows: { type: Object as PropType<SystemSpace.MeterPage>, default: () => {} },
  factorys: { type: Array as PropType<EnumProps[]>, default: () => [] },
  lines: { type: Array as PropType<EnumProps[]>, default: () => [] },
  devicetTypes: { type: Array as PropType<EnumProps[]>, default: () => [] },
  commModes: { type: Array as PropType<EnumProps[]>, default: () => [] },
  gateWays: { type: Array as PropType<EnumProps[]>, default: () => [] }
})
const emit = defineEmits(["update:modelValue", "refresh"])
// 参数
const formRef = ref<FormInstance>() // 表单实例
const checkDevice = ref<number[]>([]) // 已选择设备信息
const devices = ref<SystemSpace.DeviceList[]>([]) // 已选择设备信息
const isEdit = computed(() => Boolean(props.rows?.id)) // 是否是编辑
// 表单数据
const formValue = ref({
  factoryId: undefined as undefined | number,
  lineId: undefined as undefined | number,
  deviceId: undefined as undefined | number,
  gatewayCode: "",
  code: "",
  name: "",
  meterType: undefined as undefined | number,
  energyType: "",
  commsMode: undefined as undefined | number,
  location: "",
  modelNumber: "",
  manufacturer: "",
  productionDate: "",
  putrunDate: "",
  personCharge: "",
  rangeCurrentStop: "",
  rangeCurrentWait: "",
  rangeCurrentUpper: "",
  remark: ""
})
// 表单校验
const formRules: FormRules = {
  factoryId: [{ required: true, message: "请选择所属厂区", trigger: "change" }],
  lineId: [{ required: true, message: "请选择所属产线", trigger: "change" }],
  deviceId: [{ required: true, message: "请选择所属设备", trigger: "change" }],
  code: [{ required: true, message: "请输入设备编码", trigger: "blur" }],
  name: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
  meterType: [{ required: true, message: "请选择设备类型", trigger: "change" }],
  commsMode: [{ required: true, message: "请选择通讯模式", trigger: "change" }],
  energyType: [{ required: true, message: "请选择能源类型", trigger: "change" }]
}
const devcieOption = computed(() => {
  return devices.value.map(item => ({
    label: item.name,
    value: item.id,
    disabled: checkDevice.value.includes(item.id)
  }))
})
// 事件
const commEvent = {
  // 关闭弹窗
  onClose: () => {
    emit("update:modelValue", false)
  },
  // 获取设备信息
  getDevices: async () => {
    const { factoryId, lineId } = formValue.value
    if (!factoryId || !lineId) {
      devices.value = []
      return
    }
    const { data } = await deviceList({ factoryId, lineId })
    devices.value = data
  },
  // 获取绑定设备id
  getDevcieIds: async () => {
    if (props.rows?.id) {
      const { factoryId, lineId } = props.rows
      const { data: devciceData } = await deviceList({ factoryId, lineId })
      devices.value = devciceData
      const { data: detailData } = await meterDetail(props.rows.id)
      const {
        deviceId,
        gatewayCode,
        code,
        name,
        meterType,
        energyType,
        commsMode,
        location,
        modelNumber,
        manufacturer,
        productionDate,
        putrunDate,
        personCharge,
        rangeCurrentStop,
        rangeCurrentWait,
        rangeCurrentUpper,
        remark
      } = detailData
      formValue.value = {
        factoryId,
        lineId,
        deviceId,
        gatewayCode,
        code,
        name,
        meterType,
        energyType,
        commsMode,
        location,
        modelNumber,
        manufacturer,
        productionDate,
        putrunDate,
        personCharge,
        rangeCurrentStop: rangeCurrentStop + "",
        rangeCurrentWait: rangeCurrentWait + "",
        rangeCurrentUpper: rangeCurrentUpper + "",
        remark
      }
      return
    }
    const { data } = await deviceIdsBound()
    checkDevice.value = data
  },
  // 提交
  onSubmit: () => {
    if (!formRef.value) return
    formRef.value.validate(async valid => {
      if (!valid) return
      let res: any
      const { factoryId, lineId, meterType, commsMode, rangeCurrentStop, rangeCurrentWait, rangeCurrentUpper, deviceId } =
        formValue.value
      const params: SystemSpace.SaveMeter = {
        ...formValue.value,
        factoryId: Number(factoryId),
        lineId: Number(lineId),
        meterType: Number(meterType),
        commsMode: Number(commsMode),
        rangeCurrentStop: Number(rangeCurrentStop),
        rangeCurrentWait: Number(rangeCurrentWait),
        rangeCurrentUpper: Number(rangeCurrentUpper),
        deviceId: Number(deviceId)
      }
      if (props.rows?.id) {
        params.id = props.rows.id
        delete params.factoryId
        delete params.lineId
        delete params.deviceId
        delete params.gatewayCode
        delete params.code
        delete params.meterType
        delete params.energyType
        delete params.commsMode
        res = await modifyMeter(params)
      } else {
        res = await addMeter(params)
      }
      if (res?.code !== "200") return
      ElMessage.success("操作成功")
      commEvent.onClose()
      emit("refresh")
    })
  }
}
watch(
  () => props.modelValue,
  flag => {
    if (flag) {
      nextTick(() => {
        if (!formRef.value) return
        formRef.value.resetFields()
        commEvent.getDevcieIds()
      })
    }
  }
)
</script>

<style lang="scss" scoped></style>
